from django.core.management.base import BaseCommand, CommandError
from django import apps
from django.db import transaction

class Command(BaseCommand):
    help = "Clean init data for models which has init_data var"

    def handle(self, *args, **options):
        models = apps.apps.get_models()
        unfinished_models = []
        for model in models:
            init_data = getattr(model, 'init_data', None)
            if init_data is None or init_data == []:
                print('[%s]No init_data var, skip...' % str(model))
                continue
            with transaction.atomic():
                try:
                    model.objects.all().delete()
                except:
                    unfinished_models.append(model)
            print('[%s]Clean Init Data OK.' % str(model))

        for model in unfinished_models:
            init_data = getattr(model, 'init_data', None)
            if init_data is None:
                print('[%s]No init_data var, skip...' % str(model))
                continue
            with transaction.atomic():
                model.objects.all().delete()
            print('[%s]Clean Init Data OK.' % str(model))
